import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

function setItem(name, item) {
  localStorage.setItem(name, JSON.stringify(item))
}
function getItem(name) {
  return JSON.parse(localStorage.getItem(name) || '[]')
}

export default {
  namespaced: true,
  state: {
    cart: getItem('cart')
  },
  getters: {
    //购物车所有商品数量
    getTotalGoodsCount(state) {
      var total = 0
      state.cart.forEach(item => {
        total += item.count
      })
      return total
    },
    //购物车中被选中商品总价格
    getTotalPrice(state) {
      var totalPrice = 0
      state.cart.forEach(item => {
        if(item.selected){
          totalPrice += item.count * item.price
        }
      })
      return totalPrice
    },
    //购物车中被选中商品数量
    getTotalSelected(state) {
      var totalSelected = 0
      state.cart.forEach(item => {
        if(item.selected){
          totalSelected += item.count
        }
      })
      return totalSelected
    },
    //购物车中被选中商品列表
    getSelectedList(state) {
      var selectedList = []
      state.cart.forEach(item => {
        if(item.selected){
          selectedList.push(item)
        }
      })
      return selectedList
    }
  },
  mutations: {
    addShopcart(state, goodsinfo) {
      let flag = false
      state.cart.some(item => {
        if(item.id === goodsinfo.id) {
          item.count += parseInt( goodsinfo.count )
          flag = true
          return true
        }
      })
      if(!flag) {
        state.cart.push(goodsinfo)
      }
      console.log(state.cart)
      setItem('cart', state.cart)
    },
    delShopcart(state, arr) {
      state.cart = arr
      setItem('cart', state.cart)
    },
    countChanged(state, param){
      state.cart.some(item => {
        if(item.id === param.id) {
          item.count = parseInt( param.newCount )
          return true
        }
      })
      setItem('cart', state.cart)
    }
  },
  actions: {
  }
}
